#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <pthread.h>
#include <functional>
namespace jc
{
    static int number = 0;
    class thread
    {
        using fun_c = std::function<void()>;//function是一个类模板 function<void()>类型， 要传一个返回值为void，无参数的函数给 fun_c
        static void* Route(void* args) //如果不是非静态成员函数变量，会包含this指针，这样默认就是两个参数，会出现参数不一致的情况，所以需要改为静态函数
        {
            thread* self = static_cast<thread*>(args);
            self->EnableRuning();
            if(self->_isdetach)
                self->Deatch();
            self->_func();
            return nullptr;
        }
        void EnableRuning()
        {
            if(_isruning)
                return;
            _isruning = true;
        }

        void EnableDetach()
        {
            if(_isdetach)
                return;
            _isdetach = true;
        }

    public:
        thread(fun_c func)
            :_tid(0),
            _isruning(false),
            _isdetach(false),
            _func(func)
        {
            _name = "thread-" + std::to_string(number++);
        }

        bool Start()
        {
            if(_isruning)
            {
                std::cout << "已经运行了" << std::endl;
                return false;
            }
            int n = pthread_create(&_tid,nullptr,Route,this);
            if(n != 0)
            {
                std::cerr << "create error" << std::endl;
                return false;
            }
            return true;
        }

        bool Stop()
        {
            if(!_isruning)
                return false;
            int n = pthread_cancel(_tid);
            if(n != 0)
            {
                std::cerr << "stop error" << std::endl;
                return false;
            }
            _isruning = false;
            std::cout << "stop" << std::endl;
            return true;
        }

        bool Deatch()
        {
            if(_isdetach)
                return false;
            if(_isruning)
                pthread_detach(_tid);
            EnableDetach();
            return true;
        }
        void Join()
        {
            if(_isdetach)
            {
                std::cout << "已经分离，无法join" << std::endl;
                return;
            }
            int n = pthread_join(_tid,nullptr);
            if(n != 0)
            {
                std::cerr << "create error" << std::endl;
            }
                std::cout << "join success" << std::endl;

        }
        ~thread()
        {

        }
    private:
        pthread_t _tid;
        std::string _name;
        bool _isruning;
        bool _isdetach;
        fun_c _func;
    };
};